const lodash = require('lodash')
const loginFns = require("../common/login")
import { pageFns } from '../utils/pageHelper'
import { funcFns } from '@/puppeteer/utils/funtion'
import { ArticleDao } from '@/dao/articleDao'

const SELECTORS = { "VIDEO_INPUT": ["div[role=\"button\"] input", "div[role=\"button\"] input", "input[type=\"file\"]"], "VIDEO_CONFIRM": ".button-row .btn-post button", "TITLE_INPUT": ["div[aria-label=\"Caption\"] div[role=\"textbox\"] span", "div[role=\"textbox\"] span span"], "POST_BUTTON": [".button-row .btn-post button"] }

// 发布
async function startPost(page, content, videos, selectors) {

    let res = await pageFns.deepRetry(SELECTORS.VIDEO_INPUT, page, async (selector, page, setting) => {
        if (setting && setting.err) {
            await page.goto(page.url(), { waitUntil: 'networkidle2' })
            console.log('video goto', setting.err)
        }
        await page.waitForSelector(selector)
        await pageFns.fileUpload({ page, element: selector, files: videos })
    }, { page: page, wait: 10 * 1000 })
    if (res.err) {
        return res
    }
    await pageFns.waitAttrDisappear(page, SELECTORS.VIDEO_CONFIRM, 'disable')
    //2. 获取原始文章并填入标题
    res = await pageFns.deepRetry(SELECTORS.TITLE_INPUT, page, async (selector, page) => {
        await page.waitForSelector(selector)
        let text = await pageFns.getText(page, selector)
        if (lodash.isEmpty(text)) {
            throw new Error("Not text ", selector)
        }
        await page.$eval(selector, (span, title) => { span.textContent = title }, content);
    }, { page: page, wait: 10 * 1000 })
    if (res.err) {
        return res
    }
    //3. 提交按钮
    res = await pageFns.deepRetry(SELECTORS.POST_BUTTON, page, async (selector, page) => {
        await page.waitForSelector(selector)
        await page.click(selector)
        await pageFns.waitDisappear(page, selector)
    }, { page: page, wait: 10 * 1000 })
    if (res.err) {
        return res
    }
    return { data: "发布成功" }
}

const LOGINS = {
    LOGINBTNS: ['#header-login-button', ['#loginContainer div[role="link"] div::-p-text("邮件")', '#loginContainer div[role="link"] div::-p-text("email")'], ['#login-modal-title + div a']],
    USERNAMES: ['#loginContainer input[name="username"]'],
    NEXTSTEPS: [],
    PASSWORDS: ['#loginContainer input[type="password"]'],
    COMFIRMBTNS: ['#loginContainer button[type="submit"]'],
    UNLOGINFLAGS: ['#loginContainer', '#header-login-button']
}

async function goPost(page, task, article, rule) {
    let selectors = JSON.parse(rule.codeRule)
    if (lodash.isEmpty(selectors)) {
        return { err: "找不到发布规则:" + task.id }
    }
    let videos = funcFns.getVideos(ArticleDao.folderPath(article))
    if (lodash.isEmpty(videos)) {
        console.log("videos", funcFns.getImageAndVideos(ArticleDao.folderPath(article)))
        return { data: "找不到发布的视频" }
    }
    let res = await loginFns.checkLogin(page, task, LOGINS)
    if (res.err) {
        console.log("goPost.checkLogin", res)
        return res
    }
    // 收集图片
    try {
        let dataFields = JSON.parse(task.dataFields)
        if (lodash.isEmpty(dataFields)) {
            return { err: "没有指定的数据" }
        }
        let aiResult = JSON.parse(article.aiResult)
        let contents = []
        for (let dataField of dataFields) {
            contents.push(aiResult[task.lang][dataField])
        }
        console.log(dataFields, article, task.lang)
        return await startPost(page, contents.join("."), videos, selectors)
    } catch (err) {
        console.log("goPost", err)
        return { err: err }
    }
}

export { goPost }